package com.jhws.core.shiro.service;

import com.jhws.util.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.Cache.ValueWrapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


@Service
public class OAuthServiceImpl implements IOAuthService {

    private static final String REDIS_KEY_HEAD = "AUTH_CODE:";
    @Resource
    private RedisTemplate stringTemplate;

    @Override
    public void addAuthCode(String authCode, String username) {
        ValueOperations listOperations = stringTemplate.opsForValue();
        String key = REDIS_KEY_HEAD + authCode;
        listOperations.set(key, username);
        stringTemplate.expire(key, 10080, TimeUnit.MINUTES);
    }

    @Override
    public void addAccessToken(String accessToken, String username) {
        ValueOperations listOperations = stringTemplate.opsForValue();
        String key = REDIS_KEY_HEAD + accessToken;
        listOperations.set(key, username);
        stringTemplate.expire(key, 10080, TimeUnit.MINUTES);
    }

    @Override
    public String getUsernameByAuthCode(String authCode) {
        String key = REDIS_KEY_HEAD + authCode;
        ValueOperations listOperations = stringTemplate.opsForValue();
        return (String) listOperations.get(key);//(String)cache.get(authCode).get();
    }

    @Override
    public String getUsernameByAccessToken(String accessToken) {
        String key = REDIS_KEY_HEAD + accessToken;
        ValueOperations listOperations = stringTemplate.opsForValue();
        return (String) listOperations.get(key);
    }

    @Override
    public boolean checkAuthCode(String authCode) {
        String key = REDIS_KEY_HEAD + authCode;
        ValueOperations listOperations = stringTemplate.opsForValue();
        return StringUtils.isNotEmpty((String) listOperations.get(key));
    }

    @Override
    public boolean checkAccessToken(String accessToken) {
        String key = REDIS_KEY_HEAD + accessToken;
        ValueOperations listOperations = stringTemplate.opsForValue();
        return StringUtils.isNotEmpty((String) listOperations.get(key));
    }

    @Override
    public boolean checkClientId(String clientId) {
        //not implement yet
        return false;
    }

    @Override
    public boolean checkClientSecret(String clientSecret) {
        //not implement yet
        return false;
    }

    @Override
    public long getExpireIn() {
        return 3600 * 24 * 7L;
    }
}
